#include "playerwindow.h"
#include "ui_playerwindow.h"

#include <QDir>
#include <QFileDialog>
#include <QDebug>
#include "loginwindow.h"
PlayerWindow::PlayerWindow(QString userName,QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::PlayerWindow),userName(userName)
{
    ui->setupUi(this);
    ui->label_user->setText("当前用户为："+userName);
    player = new QMediaPlayer(this);
    playerList = new QMediaPlaylist(this);
    //关联信号与槽：play播放器 当播放歌曲的进度位置发生改变事，就会发出信号，同时发出当前播放位置在哪
    //                                      信号会发出播放的进度的位置
    //
    playerList->setPlaybackMode(QMediaPlaylist::Loop);
    connect(player,&QMediaPlayer::positionChanged,
            this,&PlayerWindow::slot_positionChanged);
    //connect(ui->listWidget_music,&QListWidget::clicked,this,&PlayerWindow::)
    vector<SongInfo> v;
    DbManager::getDbPtr()->selectHistory(v,userName);
    for(auto info :v)
    {
        historySet.insert(info);
        ui->listWidget_history->addItem(info.musicName);
    }

}

PlayerWindow::~PlayerWindow()
{
    delete ui;
}
int n=0;
//上一首
void PlayerWindow::on_pushButton_pro_clicked()
{
    n=0;
    player->pause();
    playerList->previous();
   // if(player->state() == QMediaPlayer::PausedState || player->state() == QMediaPlayer::StoppedState)


    on_pushButton_play_clicked();

}

//播放或暂停
void PlayerWindow::on_pushButton_play_clicked()
{
    QString name = ui->comboBox->currentText();

    n++;
    //播放器播放
    n=n%2;
    if(n==1)
    {
        player->play();//pause（）暂停 stop()停止
        ui->pushButton_play->setIcon(QIcon(":/icon/icon/pause.png"));
        ui->label_musicName->setText("");
        dealHistory();
    }
    else
    {
        player->pause();
        ui->pushButton_play->setIcon(QIcon(":/icon/icon/play.png"));
    }


}


//下一首
void PlayerWindow::on_pushButton_next_clicked()
{
    n=0;
    player->pause();
    playerList->next();
    //if(player->state() == QMediaPlayer::PausedState || player->state() == QMediaPlayer::StoppedState)
        on_pushButton_play_clicked();
}

//选择歌单 (目录操作 提取目录下的所有.mp3结尾的文件，显示到列表中)
void PlayerWindow::on_pushButton_music_clicked()
{
    //弹出 选择文件夹 目录存在 目录不存在
    QString path =  QFileDialog::getExistingDirectory(this,"选择歌曲目录","E:\\");
    //返回的目录字符串 要做一个空判断--》 点了取消，没有选择有限的文件夹
    if(!path.isEmpty())
    {
        QDir dir(path,"*.mp3");
        //有效的文件夹--》提取目录下的文件
          if(dir.exists()==false){qDebug()<<1;dir.mkpath(path);}
        musicNames = dir.entryList(QDir::Files,QDir::Name);
        for(auto it = musicNames.begin();it != musicNames.end();it++)
        {
            qDebug()<<*it;
           if((*it).endsWith(".mp3"))
           {
            //每一个名字 显示到列表中
            ui->listWidget_music->addItem(*it);
            QString url =path+"/"+*it;
            playerList->addMedia(QUrl(url));
            //qDebug()<<url;

           }

        }
        //列表 给 播放器对象
        player->setPlaylist(playerList);

        //播放列表 设置 当前播放的位置
        playerList->setCurrentIndex(0);
    }

}

//切换用户
void PlayerWindow::on_pushButton_account_clicked()
{

        //关闭当前窗口
        this->close();
        //显示 登录窗口
    LoginWindow *p = new LoginWindow;
}
//d                                                 参数：是信号给你发出来的，接收信号给的资源
void PlayerWindow::on_comboBox_currentIndexChanged(const QString &arg1)
{
    qDebug()<<arg1;
    if( arg1 == "顺序播放")
    {
        playerList->setPlaybackMode(QMediaPlaylist::Sequential);
    }
    else if(arg1 == "随机播放")
    {
        playerList->setPlaybackMode(QMediaPlaylist::Random);
    }
    else if(arg1 == "循环播放")
    {
        playerList->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
    }
}

void PlayerWindow::slot_positionChanged(qint64 position)
{
    qDebug()<<position;//position就是当前歌曲播放到的位置
    //1.设置滑动条的最大值 为歌曲的长度
    qint64 musicLength =  player->duration();
    ui->horizontalSlider_music->setMaximum(musicLength);

    //2.将 position设置为滑动条当前那要显示的值
    ui->horizontalSlider_music->setValue(position);

    //歌名 和 歌曲长度
    //1)获取播放的位置
    int index = playerList->currentIndex();
    //2）去容器中，根据位置 获取 歌曲
    QString fileName = musicNames.at(index);
    ui->label_musicName->setText(fileName);


    //歌曲长度[00:00 / 05:36]
    //长度是毫秒为单位
    int len  = musicLength/1000;
    int min = len /60;
    int sec = len%60;

    //实时根据播放的进度，显示播放的进度描述
    int current_min = position/1000/60;
    int current_sec = position/1000%60;

    //拼接字符 格式： [00:00 : 05:36]                           宽度2位 10进制  不够补0
    QString str = QString("[ %1:%2 : %3:%4]").arg(current_min , 2, 10,QChar('0')).
                                              arg(current_sec , 2, 10,QChar('0')).
                                              arg(min , 2, 10,QChar('0')).
                                              arg(sec , 2, 10,QChar('0'));

    ui->label_time->setText(str);

}

void PlayerWindow::on_horizontalSlider_music_sliderMoved(int position)
{
    player->setPosition(position);
}

//void PlayerWindow::on_horizontalSlider_music_sliderReleased()
//{
//    player->setPosition( player->duration());
//}

void PlayerWindow::on_horizontalSlider_music_sliderPressed()
{
    player->setPosition(player->position());

}


//                                                                      item指针：双击第几行，这个指针是指向哪行的指针
void PlayerWindow::on_listWidget_music_itemDoubleClicked(QListWidgetItem *item)
{
    //根据给我的行指针，获取当前行的
    int index = ui->listWidget_music->row(item);
    playerList->setCurrentIndex(index);
    n=0;
    on_pushButton_play_clicked();

}

void PlayerWindow::dealHistory()
{
    QString musicName = musicNames.at(playerList->currentIndex());

    SongInfo info;
    info.musicName = musicName;
    info.userName = userName;
    if(historySet.count(info) == 0)
    {
        bool ok = DbManager::getDbPtr()->insertHistory(info);
        if(ok)
        {
            //向界面列表插入一条
            ui->listWidget_history->addItem(musicName);
            //set容器插入一个元素
            historySet.insert(info);
        }
    }


}

void PlayerWindow::on_horizontalSlider_voice_sliderMoved(int position)
{
    player->setVolume(position);
}
